<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: UCToo <contact@uctoo.com>
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace catcher\command\Tools;

use catcher\CatchAdmin;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use QL\QueryList;
use think\facade\Log;

/**
 * 生成CRUD页面
 *
 * Class CompressPackageCommand
 * @package catcher\command\Tools
 */
class CreateElmformCommand extends Command
{
    protected $table;

    protected function configure()
    {
        // 指令配置
        $this->setName('create:elmform')
            ->addArgument('table', Argument::REQUIRED, 'create pages')
            ->addOption('configjson', '-c', Option::VALUE_OPTIONAL, 'config json data')
            ->addOption('module', '-m', Option::VALUE_OPTIONAL, 'module name')
            ->addOption('path', '-p', Option::VALUE_OPTIONAL, 'output path')
            ->addOption('formjson', '-j', Option::VALUE_OPTIONAL, 'form json data')
            ->addOption('templatefilename', '-t', Option::VALUE_OPTIONAL, 'template filename')
            ->addOption('templatecode', '-e', Option::VALUE_OPTIONAL, 'template code')
            ->addOption('saveoutputauth', '-a', Option::VALUE_OPTIONAL, 'can save output file')
            ->setDescription('Just for catchAdmin create element UI pages');
    }

    protected function execute(Input $input, Output $output)
    {
        $table = $input->getArgument('table');
        $module = $input->getOption('module');
        $path = $input->getOption('path');
        $formjson = $input->getOption('formjson');
        $configjson = $input->getOption('configjson');
        $templatefilename = $input->getOption('templatefilename');
        $templatecode = $input->getOption('templatecode');
        $saveoutputauth = $input->getOption('saveoutputauth');
        //输出配置
        $pathArray = json_decode($path,true);
        $formArray = json_decode($formjson,true);
        //用户模板配置
        $configArray = json_decode($configjson,true);
        //表的字段
        $tableFields = $formArray['table_fields'];

        Log::write($saveoutputauth,'debug');
        //controller url
        $class = $formArray['controller']['controller'];
        $class = explode('\\', $class);
        $controllerName = lcfirst(array_pop($class));
        try{
            //加载crud页面模板
            if($templatecode){
                $stub = $templatecode;
            }elseif($templatefilename){
                $stub = file_get_contents(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR .'elm' . DIRECTORY_SEPARATOR . $templatefilename);
            }
            //加载router.js模板
            $routerjsstub = file_get_contents(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR .'elm' . DIRECTORY_SEPARATOR . 'routerjs.stub');
            //用QueryList处理模板,会自动把自闭合标签都处理成闭合标签，例如<input />输出成<input></input>，对功能没影响
            //由于QueryList无法处理 @click、@close等@开头的标签事件，因此模板中所有@都用el-event-at_ 人工替换了
            $ql = QueryList::html($stub);
            //循环所有字段,组装queryParam
            $queryParamHtml = '';
            $dropdownItemHtml = '';
            $tableColumnHtml = '';
            $formItemHtml = '';
            $replaceFields = '';
            foreach($configArray as $k => $v){
                // 获取第一个el-form-item元素,用于组装组装queryParam,第一个搜索el-form和第二个编辑el-form算法一致仅参数不同
                $queryParamNode = $ql->find('el-form:eq(0) el-form-item:eq(0)');
                $queryParamNode->attr('prop',$v['field']);
                $queryParamNode->attr('label',$v['comment']);
                $queryParamInputNode = $ql->find('el-form:eq(0) el-form-item:eq(0) el-input:eq(0)');
                $queryParamInputNode->attr('v-model','queryParam.'.$v['field']);
                $queryParamInputNode->attr('placeholder',$v['comment']);
                $queryParamInputNode->attr('type',$v['inputType']);//兼容用户配置了textarea控件类型
                $queryParamHtml = $queryParamHtml.$queryParamNode->htmlOuter();
                // 获取第一个el-checkbox-group元素,用于组装el-dropdown-item
                $dropdownItemNode = $ql->find('el-checkbox-group:eq(0) el-dropdown-item:eq(0)');
                $dropdownItemCheckNode = $ql->find('el-checkbox-group:eq(0) el-dropdown-item:eq(0) el-checkbox');
                $dropdownItemCheckNode->attr('label',$v['field']);
                $dropdownItemHtml = $dropdownItemHtml.$dropdownItemNode->htmlOuter();
                // 获取第二个el-table-column元素,用于组装el-table-column
                $tableColumnNode = $ql->find('el-table-column:eq(1)');
                $tableColumnNode->attr('prop',$v['field']);
                $tableColumnNode->attr('label',$v['comment']);
                $tableColumnHtml = $tableColumnHtml.$tableColumnNode->htmlOuter();
                // 获取第二个el-form-item元素,用于组装el-form-item
                $formItemNode = $ql->find('el-form:eq(1) el-form-item:eq(0)');
                $formItemNode->attr('prop',$v['field']);
                $formItemNode->attr('label',$v['comment']);
                $formItemInputNode = $ql->find('el-form:eq(1) el-form-item:eq(0) el-input');
                $formItemInputNode->attr('v-model','formFieldsData.'.$v['field']);
                $formItemInputNode->attr('placeholder',$v['comment']);
                $formItemInputNode->attr('type',$v['inputType']);//兼容用户配置了textarea控件类型

                $formItemHtml = $formItemHtml.$formItemNode->htmlOuter();
                $replaceFields = $replaceFields.$v['field'].":'',";
            }
            //组装的queryParamHtml替换模板中的queryParam,
            $ql->find('el-form:eq(0) el-form-item:eq(0)')->replaceWith($queryParamHtml);
            //组装的dropdownItemHtml替换模板中的dropdownItem,
            $ql->find('el-checkbox-group:eq(0) el-dropdown-item:eq(0)')->replaceWith($dropdownItemHtml);
            //组装的tableColumnHtml替换模板中的tableColumn,
            $ql->find('el-table-column:eq(1)')->replaceWith($tableColumnHtml);
            //组装的formItemHtml替换模板中的formItem,
            $ql->find('el-form:eq(1) el-form-item:eq(0)')->replaceWith($formItemHtml);

            $html = $ql->getHtml();
            //el-event-at_ 替换回 @
            $html = str_replace("el-event-at_","@",$html);
            //替换表格字段
            $html = str_replace("el-js-replace-fields",$replaceFields,$html);
            //替换url
            $html = str_replace("el-js-replace-url",$controllerName,$html);
            //替换模板名
            $html = str_replace("el-js-replace-formName",$pathArray['filename'],$html);
            //替换模块名
            $html = str_replace("el-js-replace-module",$pathArray['module'],$html);

            //替换routerjs.stub中的变量
            $routerjs = str_replace("vue-replace-module",$pathArray['module'],$routerjsstub);
            $routerjs = str_replace("vue-replace-controller",$pathArray['filename'],$routerjs);  //默认的目录名和table名相对应
            //保存crud页面
            if($pathArray['module'] && $pathArray['path'] && $pathArray['filename'] && $saveoutputauth){
                file_put_contents(CatchAdmin::moduleViewDirectory($pathArray['module'],$pathArray['path']) . $pathArray['filename'] .'.vue', $html);
            }
            //保存router.js
            //file_put_contents(CatchAdmin::moduleRouterjsDirectory($module) . 'router' .'.js', $routerjs);
        }catch (\Throwable $e) {
            $output->error($e->getMessage(). ': Error happens at ' .$e->getFile() .  ' '. $e->getLine() . '行');
        }
        $output->writeln($html);
    }
}

